<template>
  <div class="particulate-monitor">
    <Title :title="title" />
    <div ref="chartContainer" class="chart-container"></div>
    <div class="update-time">
      最后更新时间：{{ lastUpdateTime }}
    </div>
  </div>
</template>

<script setup>
import { Bar } from '@antv/g2plot';
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { get } from '@/utils/request';
import Title from './Title.vue';
import moment from 'moment';

const title = ref('南通市崇川区实时颗粒物监测');
const chartContainer = ref(null);
const chartData = ref([]);
const lastUpdateTime = ref('');
let chartInstance = null;
let refreshTimer = null;

// 处理API数据
const processData = (rawData) => {
  return rawData.map(item => ({
    district: item.district || '未知区域',
    pm25: Math.round(item.pm25) || 0,
    pm10: Math.round(item.pm10) || 0,
    time: item.time || moment().format('YYYY-MM-DD HH:mm:ss')
  }));
};

// 生成图表数据
const generateChartData = (processedData) => {
  return processedData.flatMap(item => [
    {
      name: item.district,
      type: 'PM2.5',
      value: item.pm25,
      unit: 'μg/m³'
    },
    {
      name: item.district,
      type: 'PM10',
      value: item.pm10,
      unit: 'μg/m³'
    }
  ]);
};

// 初始化图表
const initChart = () => {
  if (!chartContainer.value) return;

  chartInstance = new Bar(chartContainer.value, {
    data: chartData.value,
    xField: 'value',
    yField: 'name',
    seriesField: 'type',
    isGroup: true,
    color: ['#5B8FF9', '#5AD8A6'], // PM2.5蓝色, PM10绿色
    marginRatio: 0.5,
    padding: [30, 20, 60, 50],
    
    // 坐标轴配置
    xAxis: {
      title: {
        text: '浓度 (μg/m³)',
        style: {
          fill: '#666',
          fontSize: 12
        }
      },
      label: {
        formatter: (v) => `${v}`,
        style: {
          fill: '#666'
        }
      },
      grid: {
        line: {
          style: {
            stroke: '#f0f0f0',
            lineDash: [4, 2]
          }
        }
      }
    },
    
    yAxis: {
      title: {
        text: '监测点位',
        style: {
          fill: '#666',
          fontSize: 12
        }
      },
      label: {
        style: {
          fill: '#666'
        }
      }
    },
    
    // 条形样式
    barStyle: {
      radius: [2, 2, 0, 0]
    },
    
    // 标签配置
    label: {
      position: 'middle',
      style: {
        fill: '#fff',
        fontSize: 10,
        fontWeight: 'bold'
      },
      formatter: (datum) => `${datum.value}`
    },
    // 提示框配置
    tooltip: {
      shared: true,
      showCrosshairs: true,
      domStyles: {
        'g2-tooltip': {
          background: '#fff',
          boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
          borderRadius: '4px'
        }
      },
      formatter: (datum) => ({
        name: `${datum[0].data.name} ${datum[0].data.type}`,
        value: `${datum[0].data.value} μg/m³`
      })
    },
    
    // 图例配置
    legend: {
      position: 'bottom',
      itemName: {
        style: {
          fill: '#666',
          fontSize: 12
        }
      }
    },
    
    // 动画配置
    animation: {
      appear: {
        animation: 'scale-in-x',
        duration: 800
      },
      update: {
        animation: 'path-in',
        duration: 600
      }
    },
    
    // 交互配置
    interactions: [
      { type: 'element-active' },
      { type: 'legend-filter' }
    ]
  });

  chartInstance.render();
};

// 获取实时数据
const fetchData = async () => {
  try {
    const res = await get('/api/particulate-matter/nantong/chongchuan', {
      minutes: 5,
      limit: 10
    });
    
    if (res.data?.list) {
      const processed = processData(res.data.list);
      chartData.value = generateChartData(processed);
      lastUpdateTime.value = moment().format('YYYY-MM-DD HH:mm:ss');
      
      if (chartInstance) {
        chartInstance.update({
          data: chartData.value
        });
      } else {
        initChart();
      }
    }
  } catch (error) {
    console.error('获取数据失败:', error);
    // 使用模拟数据
    generateMockData();
  }
};

// 生成模拟数据
const generateMockData = () => {
  const districts = [
    '狼山镇街道', '钟秀街道', '文峰街道', 
    '观音山街道', '学田街道', '新城桥街道'
  ];
  
  const mockData = districts.map(district => ({
    district,
    pm25: Math.round(20 + Math.random() * 30),
    pm10: Math.round(30 + Math.random() * 50),
    time: moment().format('YYYY-MM-DD HH:mm:ss')
  }));
  
  chartData.value = generateChartData(mockData);
  lastUpdateTime.value = moment().format('YYYY-MM-DD HH:mm:ss');
  
  if (chartInstance) {
    chartInstance.changeData(chartData.value);
  } else {
    initChart();
  }
};

// 定时刷新
const startAutoRefresh = () => {
  refreshTimer = setInterval(fetchData, 60 * 1000); // 每分钟刷新一次
};

// 初始化
onMounted(async () => {
  await fetchData();
  startAutoRefresh();
});

// 清理
onBeforeUnmount(() => {
  if (refreshTimer) clearInterval(refreshTimer);
  if (chartInstance) chartInstance.destroy();
});
</script>

<style scoped>
.particulate-monitor {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.chart-container {
  flex: 1;
  min-height: 300px;
}

.update-time {
  text-align: right;
  padding: 8px 16px;
  font-size: 12px;
  color: #999;
}
</style>
    